package com.kc.business.service.impl;

import cn.hutool.core.date.DateUtil;
import com.kc.business.domain.*;
import com.kc.business.domain.dto.BizBusinessOrderGoodsDTO;
import com.kc.business.domain.dto.BizBusinessOrderInfoDTO;
import com.kc.business.domain.dto.BizOrderInfoDTO;
import com.kc.business.mapper.BizBusinessGoodsMapper;
import com.kc.business.mapper.BizBusinessOrderGoodsMapper;
import com.kc.business.mapper.BizBusinessOrderMapper;
import com.kc.business.mapper.BizUserBusinessCouponMapper;
import com.kc.business.service.IBizBusinessOrderService;
import com.kc.common.utils.CommonUtils;
import com.kc.system.service.ISysDictDataService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;

/**
 * 商家订单service实现类
 */
@Service
@Slf4j
public class BizBusinessOrderServiceImpl implements IBizBusinessOrderService {
    @Resource
    private BizBusinessGoodsMapper kcBusinessGoodsMapper;
    @Resource
    private BizUserBusinessCouponMapper kcUserBusinessCouponMapper;
    @Resource
    private BizBusinessOrderMapper kcBusinessOrderMapper;
    @Resource
    private BizBusinessOrderGoodsMapper kcBusinessOrderGoodsMapper;
    @Resource
    private ISysDictDataService dictDataService;

//    @Resource
//    private KcMqConsumeFailedMessageService consumeFailedMessageService;
//    @Resource
//    private KcUserService kcUserService;
//    @Resource
//    private WxPartnerService wxPartnerService;
//    @Resource
//    private KcBusinessInfoService kcBusinessInfoService;


    /**
     * 根据商品
     * @param ids
     * @return
     */
    @Override
    public List<BizBusinessGoods> getGoodsListByGoodsIds(Integer[] ids) {
        List<BizBusinessGoods> goodsList = new ArrayList<>();

        BizBusinessGoods bizBusinessGoods = new BizBusinessGoods();
        bizBusinessGoods.setStatus(1);
        bizBusinessGoods.setIsDeleted(0);
        for (Integer id : ids) {
            bizBusinessGoods.setId(id);
            BizBusinessGoods kcBusinessGoods = kcBusinessGoodsMapper.selectOne(bizBusinessGoods);
            if(kcBusinessGoods != null){
                goodsList.add(kcBusinessGoods);
            }
        }
        return goodsList;
    }
    /**
     * 商家订单列表
     * @param businessId
     * @param status
     * @return
     */
    @Override
    public List<BizBusinessOrderInfoDTO> orderList(Integer businessId, Integer status, BizScenicBusiness kcScenicBusiness) {

        List<BizBusinessOrderInfoDTO> kcBusinessOrderInfoDTOList = new ArrayList<>();
        //查询订单列表
        List<BizBusinessOrder> kcBusinessOrderList = this.getOrderList(businessId,status);
        //获取商家信息

        kcBusinessOrderList.forEach(kcBusinessOrder -> {
            BizBusinessOrderInfoDTO kcBusinessOrderInfoDTO= new BizBusinessOrderInfoDTO();
            //订单下商品列表
            List<BizBusinessOrderGoods> kcBusinessOrderGoodsList = this.getOrderGoodsList(kcBusinessOrder.getId());
            Integer goodsNum = 0;//订单下商品总数量
            List<BizBusinessOrderGoodsDTO> goodsList = new ArrayList<>();
            for(BizBusinessOrderGoods kcBusinessOrderGoods : kcBusinessOrderGoodsList){
                goodsNum += kcBusinessOrderGoods.getGoodsNum();
                goodsList.add(new BizBusinessOrderGoodsDTO(kcBusinessOrderGoods.getGoodsName(),kcBusinessOrderGoods.getGoodsPrice(),
                        kcBusinessOrderGoods.getGoodsNum(),kcBusinessOrderGoods.getGoodsImage(),kcBusinessOrderGoods.getGoodsIntro()));
            }
            kcBusinessOrderInfoDTO.setGoodsList(goodsList);
            Long days = CommonUtils.getDayDiff(kcBusinessOrderGoodsList.get(0).getUseStartTime(),kcBusinessOrderGoodsList.get(0).getUseEndTime());
            Long expireDate = 0l;//确认过期秒数
            if(kcBusinessOrder.getStatus() == 1){
                expireDate =  CommonUtils.getBetweenSecond(kcBusinessOrder.getPayDate(), kcBusinessOrder.getConfirmDate());
            }
            String statusName = "";
            //订单信息处理
            if(kcScenicBusiness.getMainTypeId() == 1 && kcBusinessOrder.getStatus() == 3){
                statusName = dictDataService.selectDictLabel("business_restaurant_use_status",kcBusinessOrder.getStatus().toString());
            }
            BizOrderInfoDTO kcOrderInfoDTO = new BizOrderInfoDTO(kcBusinessOrder.getId(), kcBusinessOrder.getOrderSn(),
                    "", "",
                    kcBusinessOrderGoodsList.get(0).getUseUserNum(),
                    kcBusinessOrderGoodsList.get(0).getGoodsNum(), days, kcBusinessOrder.getCouponMoney(),
                    expireDate, kcBusinessOrder.getStatus(),
                    statusName,kcBusinessOrder.getRefundReason(),kcBusinessOrder.getRefundRemark());
            //(Integer orderId, String orderSn, String createTime, String useStartTime, String useEndTime,
            // Integer useUserNum, Integer goodsNum, Long days, String reservedName, String reservedMobile, Double couponMoney,
            // String couponId, Double payMoney, Double orderMoney, Long expireDate, Integer status, String statusName)
            String[] useArr = this.getOrderUseDate(kcBusinessOrderGoodsList.get(0).getUseStartTime(),kcBusinessOrderGoodsList.get(0).getUseEndTime(),kcScenicBusiness,kcOrderInfoDTO);
            kcOrderInfoDTO.setUseStartTime(useArr[0]);
            kcOrderInfoDTO.setUseEndTime(useArr[1]);
            kcOrderInfoDTO.setStartWeek(useArr[2]);
            kcOrderInfoDTO.setEndWeek(useArr[3]);
            kcOrderInfoDTO.setGoodsNum(goodsNum);
            kcOrderInfoDTO.setOrderMoney(kcBusinessOrder.getOrderMoney());
            kcOrderInfoDTO.setPayMoney(kcBusinessOrder.getPayMoney());
            kcOrderInfoDTO.setReservedName(kcBusinessOrderGoodsList.get(0).getReservedName());
            kcOrderInfoDTO.setReservedMobile(kcBusinessOrderGoodsList.get(0).getReservedMobile());
            kcOrderInfoDTO.setCommentId(kcBusinessOrder.getCommentId());
            kcOrderInfoDTO.setRefundApplyDate(kcBusinessOrder.getRefundApplyDate());
            if(!kcBusinessOrder.getCommentId().equals(0)){
                kcOrderInfoDTO.setCommentStatus(1);
            }
            if(kcBusinessOrder.getStatus() == 4){
                kcOrderInfoDTO.setRefundExpire(CommonUtils.getBetweenSecond(kcBusinessOrder.getRefundApplyDate(), kcBusinessOrder.getRefundConfirmDate()));
            }
            kcBusinessOrderInfoDTO.setBizOrderInfoDTO(kcOrderInfoDTO);
//            if(kcBusinessOrder.getStatus() == 4){
//                kcBusinessOrderInfoDTO.setRefuseReason(dictDataService.selectDictLabel("business_order_refund_refuse_reason"));
//            }

            kcBusinessOrderInfoDTOList.add(kcBusinessOrderInfoDTO);

        });
        return kcBusinessOrderInfoDTOList;
    }

    /**
     * 获取订单使用时间
     * @param getUseStartTime
     * @param getUseEndTime
     * @param kcScenicBusiness
     * @return
     */
    @Override
    public String[] getOrderUseDate(String getUseStartTime,String getUseEndTime,BizScenicBusiness kcScenicBusiness,BizOrderInfoDTO kcOrderInfoDTO){
        String[] useArr = new String[4];
        Date startDate = DateUtil.parse(getUseStartTime);
        String startWeek = "";
        String endWeek = "";
        if(kcScenicBusiness.getMainTypeId() == 2) {
            Date endDate = DateUtil.parse(getUseEndTime);
            getUseStartTime = (DateUtil.month(startDate) + 1) + "月" + DateUtil.dayOfMonth(startDate) + "日 ";
            getUseEndTime = (DateUtil.month(endDate) + 1) + "月" + DateUtil.dayOfMonth(endDate) + "日 ";
            startWeek = CommonUtils.getWeek(startDate);
            endWeek = CommonUtils.getWeek(endDate);

        }else if(kcScenicBusiness.getMainTypeId() == 1){
            getUseStartTime = DateUtil.hour(startDate,true)+"点"+DateUtil.minute(startDate)+"分";
            startWeek = CommonUtils.getWeek(startDate);
            getUseEndTime = "";
        }else{
            getUseStartTime = getUseStartTime.substring(0,10);
            startWeek = CommonUtils.getWeek(startDate);
            getUseEndTime = "";
        }
        useArr[0] = getUseStartTime;
        useArr[1] = getUseEndTime;
        useArr[2] = startWeek;
        useArr[3] =endWeek;
        return useArr;
    }
    /**
     * 获取订单表数据列表
     * @param businessId
     * @param status
     * @return
     */
    @Override
    public List<BizBusinessOrder> getOrderList(Integer businessId,Integer status){

        BizBusinessOrder businessOrder = new BizBusinessOrder();
//        if(status != 9999){
//            businessOrder.setStatus(status);
//        }
        businessOrder.setStatus(status);
        businessOrder.setBusinessId(businessId);
//        if(status.equals(-1)){
//            wrapper.notIn(BizBusinessOrder::getRefundStatus,0);
//            wrapper.notIn(BizBusinessOrder::getStatus,0);
//        }
        return kcBusinessOrderMapper.getOrderList(businessOrder);
    }

    /**
     * 获取订单表数据详情
     * @param orderId
     * @return
     */
    @Override
    public BizBusinessOrder getOrderInfo(Integer orderId,Integer userId){
        BizBusinessOrder bizBusinessOrder = new BizBusinessOrder();
        bizBusinessOrder.setId(orderId);
        return kcBusinessOrderMapper.selectOne(bizBusinessOrder);
    }
    /**
     * 订单取消
     * @param kcBusinessOrder
     * @param userId
     * @return
     */
    @Override
    public Integer orderCancel(BizBusinessOrder kcBusinessOrder, Integer userId) {
//        if(userId != 0 && !kcBusinessOrder.getUserId().equals(userId)){
//            return null;
//           // throw new CustomizeException(ReturnMessageEnum.COMMON_PARAM_ERROR.getMessage());
//        }
//        if(kcBusinessOrder.getStatus() == 0 || kcBusinessOrder.getStatus() == 1){
//            //退款不需要审核(关闭订单)
//            //todo 此处需要新增退款逻辑
//            if(kcBusinessOrder.getStatus() == 1){
//                kcBusinessOrder.setRefundNo(CommonUtils.getOrderSn("RF"));
//                kcBusinessOrder.setRefundStatus(2);
//
//                //todo 执行退款操作
//                // 调用微信退款
//                BigDecimal refundPrice = new BigDecimal(kcBusinessOrder.getPayMoney().toString());
//                int refundAmount = refundPrice.multiply(new BigDecimal(100)).setScale(0).intValue();
//                int refundFee = new BigDecimal(kcBusinessOrder.getPayMoney().toString()).multiply(new BigDecimal(100)).setScale(0).intValue();
//                // 调用微信
//                BizScenicBusiness kcScenicBusiness = .getInfoById(kcBusinessOrder.getBusinessId(),0);
//                log.info("退款開始{},{},{},{}", kcBusinessOrder.getOrderSn(), kcBusinessOrder.getRefundNo(), refundAmount, refundAmount);
//                Map<String, Object> resultMap = wxPartnerService.refund(kcScenicBusiness.getSubMchid(),
//                        refundAmount, refundAmount,
//                        kcBusinessOrder.getOrderSn(), kcBusinessOrder.getRefundNo(), "/businessCenterOrder/refundCallBack");
//                log.info("退款結束");
//
//
//                log.info("[票务订单退款]，调起微信返回数据{}",resultMap);
//                if (resultMap != null && HttpStatus.HTTP_OK == Integer.parseInt(String.valueOf(resultMap.get("httpStatusCode"))))  {
//                        //改为退款中状态
//                        kcBusinessOrderMapper.updateById(kcBusinessOrder);
//                        return 1;
//                    } else {
//                        // 微信返回失败时回退状态
//                        log.info("[调起微信退款失败]，订单信息:{}",kcBusinessOrder);
//                    }
//
//
//            }
//            kcBusinessOrder.setStatus(-1);
//            this.updateOrder(kcBusinessOrder,userId);
//        }else if (kcBusinessOrder.getStatus() == 2){
//            //退款需要审核
//            kcBusinessOrder.setRawStatus(kcBusinessOrder.getStatus());
//            kcBusinessOrder.setStatus(4);
//            kcBusinessOrder.setRefundNo(CommonUtils.getOrderSn("RF"));
//            this.updateOrder(kcBusinessOrder,userId);
//        }else{
//            //不能退款
//            throw new CustomizeException(ReturnMessageEnum.COMMON_PARAM_ERROR.getMessage());
//        }
//        //优惠券返还
//        if(!kcBusinessOrder.getCouponId().equals("")){
//            this.backCoupon(kcBusinessOrder.getCouponId());
//        }

        return 1;
    }

    /**
     * 订单数据修改
     * @param kcBusinessOrder
     * @param userId
     * @return
     */
    @Override
    public Integer updateOrder(BizBusinessOrder kcBusinessOrder, Integer userId) {
//        if(userId != 0 && !kcBusinessOrder.getUserId().equals(userId)){
//            return 0;
//        }
        return kcBusinessOrderMapper.updateByPrimaryKeySelective(kcBusinessOrder);
    }

    /**
     * 获取类别下订单数量
     * @param businessId
     * @param status
     * @return
     */
    @Override
    public Integer getCountNum(Integer businessId, Integer status) {
        BizBusinessOrder bizBusinessOrder = new BizBusinessOrder();
        bizBusinessOrder.setBusinessId(businessId);
        bizBusinessOrder.setStatus(status);
        return kcBusinessOrderMapper.selectCount(bizBusinessOrder);
    }

    /**
     * 根据订单状态获取订单列表
     * @param status
     * @return
     */
    @Override
    public List<BizBusinessOrder> getOrderListByStatus(Integer status) {
        BizBusinessOrder bizBusinessOrder = new BizBusinessOrder();
        bizBusinessOrder.setStatus(status);
        return kcBusinessOrderMapper.select(bizBusinessOrder);
    }

    @Override
    public void autoCancelAsync(List<BizBusinessOrder> waitingReceiveOrders) {

    }

    @Override
    public void autoWatConfirmCancelAsync(List<BizBusinessOrder> waitingReceiveOrders) {

    }


    /**
     * 根据订单号获取订单详情
     * @param orderSn
     * @return
     */
    @Override
    public BizBusinessOrder getInfoByOrdersn(String orderSn) {
        BizBusinessOrder bizBusinessOrder = new BizBusinessOrder();
        bizBusinessOrder.setOrderSn(orderSn);
        return kcBusinessOrderMapper.selectOne(bizBusinessOrder);
    }




    /**
     * 确认退款
     * @param order
     * @return
     */
    public Integer confirmRefund(BizBusinessOrder order){
        //todo 调整为消息队列APP端执行退款
//        if(order.getStatus() == 4 && order.getRefundStatus() == 0){
//            // 调用微信退款
//            BigDecimal refundPrice = new BigDecimal(order.getPayMoney().toString());
//            int refundAmount = refundPrice.multiply(new BigDecimal(100)).setScale(0).intValue();
//            int refundFee = new BigDecimal(order.getPayMoney().toString()).multiply(new BigDecimal(100)).setScale(0).intValue();
//            // 调用微信
//            KcScenicBusiness kcScenicBusiness = kcBusinessInfoService.getInfoById(order.getBusinessId(),0);
//            log.info("退款開始{},{},{},{}", order.getOrderSn(), order.getRefundNo(), refundAmount, refundAmount);
//            Map<String, Object> resultMap = wxPartnerService.refund(kcScenicBusiness.getSubMchid(),
//                    refundAmount, refundAmount,
//                    order.getOrderSn(), order.getRefundNo(), "/businessCenterOrder/refundCallBack");
//            log.info("退款結束");
//            if (resultMap != null && HttpStatus.HTTP_OK == Integer.parseInt(String.valueOf(resultMap.get("httpStatusCode")))) {
//                    //改为退款中状态
//                    order.setRefundStatus(2);
//                    kcBusinessOrderMapper.updateById(order);
//                    //优惠券返还
//                    if(!order.getCouponId().equals("")){
//                        this.backCoupon(order.getCouponId());
//                    }
//                    return 1;
//                } else {
//                    // 微信返回失败时回退状态
//                    log.info("[调起微信退款失败]，订单信息:{}",order);
//                }
//
//        }else{
//            log.info("[商家订单自动退款]，订单信息错误:{}",order);
//        }
        return 1;
    }
    /**
     * 代金券返还
     * @param couponId
     * @return
     */
    public Integer backCoupon(String couponId){
//        LambdaQueryWrapper<KcUserBusinessCoupon> wrapper = new LambdaQueryWrapper<>();
//        wrapper.eq(KcUserBusinessCoupon::getId,couponId);
//
//        KcUserBusinessCoupon kcUserBusinessCoupon = kcUserBusinessCouponMapper.selectOne(wrapper);
        BizUserBusinessCoupon bizUserBusinessCoupon = new BizUserBusinessCoupon();
        bizUserBusinessCoupon.setId(couponId);
        bizUserBusinessCoupon.setStatus(0);
        return kcUserBusinessCouponMapper.updateByPrimaryKeySelective(bizUserBusinessCoupon);
    }
    /**
     * 获取订单下商品列表
     * @param orderId
     * @return
     */
    @Override
    public List<BizBusinessOrderGoods> getOrderGoodsList(Integer orderId){
        BizBusinessOrderGoods bizBusinessOrderGoods = new BizBusinessOrderGoods();
        bizBusinessOrderGoods.setOrderId(orderId);
        return kcBusinessOrderGoodsMapper.select(bizBusinessOrderGoods);
    }
}
